from fastapi import APIRouter, Depends, HTTPException, status, Request, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from app.database.database import get_db
from app.models.models import SysUser, SysMenu
from app.schemas.schemas import UserResponse, UserCreate, UserUpdate, MenuTreeNode
from app.utils.auth import get_current_active_user, get_password_hash
from app.utils.menu_utils import build_menu_tree
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse, JSONResponse
import json

router = APIRouter()
templates = Jinja2Templates(directory="app/templates")

# 页面路由 - 返回HTML页面
@router.get("/users", response_class=HTMLResponse)
async def get_users_page(request: Request):
    return templates.TemplateResponse("users.html", {"request": request})

# API路由 - 获取用户信息
@router.get("/api/user/info")
async def get_user_info(current_user: SysUser = Depends(get_current_active_user)):
    """获取当前登录用户的基本信息"""
    return {
        "id": current_user.id,
        "name": current_user.name,
        "email": current_user.email,
        "is_admin": current_user.is_admin,
    }

# API路由 - 检查是否管理员
@router.get("/api/user/is_admin")
async def is_admin(current_user: SysUser = Depends(get_current_active_user)):
    """检查当前用户是否为管理员"""
    return {"is_admin": current_user.is_admin == 1}

# API路由 - 返回JSON数据
@router.get("/api/users")
async def get_users(
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user),
    skip: int = 0, 
    limit: int = 10,
    name: Optional[str] = None
):
    if current_user.is_admin == 0:
        raise HTTPException(status_code=403, detail="无权访问")
    
    query = db.query(SysUser)
    if name:
        query = query.filter(SysUser.name.like(f"%{name}%"))
    
    total = query.count()
    users = query.offset(skip).limit(limit).all()
    
    total_pages = (total + limit - 1) // limit  # 计算总页数（向上取整）
    current_page = skip // limit + 1 if skip > 0 else 1  # 计算当前页码
    
    # 转换users为字典列表，以便添加分页信息
    user_list = []
    for user in users:
        user_dict = {
            "id": user.id,
            "name": user.name,
            "email": user.email,
            "remark": user.remark,
            "is_admin": user.is_admin,
            "is_active": user.is_active,
            "created_at": user.created_at,
            "updated_at": user.updated_at,
        }
        user_list.append(user_dict)
    
    # 返回带分页信息的响应
    return {
        "items": user_list,
        "total": total,
        "page": current_page,
        "pages": total_pages,
        "size": limit
    }

@router.get("/api/users/{user_id}", response_model=UserResponse)
async def get_user(
    user_id: int, 
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user)
):
    if current_user.is_admin == 0 and current_user.id != user_id:
        raise HTTPException(status_code=403, detail="无权访问")
    
    user = db.query(SysUser).filter(SysUser.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    return user

@router.put("/api/users/{user_id}", response_model=UserResponse)
async def update_user(
    user_id: int, 
    user_update: UserUpdate, 
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user)
):
    if current_user.is_admin == 0 and current_user.id != user_id:
        raise HTTPException(status_code=403, detail="无权访问")
    
    db_user = db.query(SysUser).filter(SysUser.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    update_data = user_update.dict(exclude_unset=True)
    if "password" in update_data and update_data["password"]:
        update_data["password"] = get_password_hash(update_data["password"])
    
    for key, value in update_data.items():
        setattr(db_user, key, value)
    
    db.commit()
    db.refresh(db_user)
    return db_user

@router.delete("/api/users/{user_id}")
async def delete_user(
    user_id: int, 
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user)
):
    if current_user.is_admin == 0:
        raise HTTPException(status_code=403, detail="无权访问")
    
    db_user = db.query(SysUser).filter(SysUser.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    # 防止删除自己
    if current_user.id == user_id:
        raise HTTPException(status_code=400, detail="不能删除当前登录用户")
    
    db.delete(db_user)
    db.commit()
    return {"message": "用户已删除"}

@router.get("/api/users/{user_id}/menus")
async def get_user_menus(
    user_id: int, 
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user)
):
    if current_user.is_admin == 0 and current_user.id != user_id:
        raise HTTPException(status_code=403, detail="无权访问")
    
    user = db.query(SysUser).filter(SysUser.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    all_menus = db.query(SysMenu).filter(SysMenu.is_active == 1).all()
    menu_tree = build_menu_tree(all_menus)
    
    user_menu_ids = []
    if user.menu_json:
        try:
            user_menu_ids = json.loads(user.menu_json)
        except:
            user_menu_ids = []
    
    return {"menu_tree": menu_tree, "user_menu_ids": user_menu_ids}

@router.put("/api/users/{user_id}/menus")
async def update_user_menus(
    user_id: int, 
    menu_ids: List[int], 
    db: Session = Depends(get_db), 
    current_user: SysUser = Depends(get_current_active_user)
):
    if current_user.is_admin == 0:
        raise HTTPException(status_code=403, detail="无权访问")
    
    user = db.query(SysUser).filter(SysUser.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    user.menu_json = json.dumps(menu_ids)
    db.commit()
    db.refresh(user)
    
    return {"message": "用户菜单权限已更新"} 